/*
 * This file is part of quickLoad, a software for gamers
 *
 * Copyright (C) 2005-2008 Lucas Romero
 *
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>.
 */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections.Specialized;
using System.Web;
using System.Net;
using System.Data.SQLite;


namespace QuickLoad.UI
{
    public partial class FormCookieSelect : Form
    {
        public FormCookieSelect()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }
        string CookieRegex = @"COOKIE\s(.*?)\sesl.eu.*\s.*\s(\d+)\s(\d+)\s(\d+)\s(\d+)\s";
        string CookieFileRegex = @".*?@esl(\[\d+\])*.txt";
        string FFCookieRegex = @".esl.eu\s.*\s/\s.*\s(\d+)\sCOOKIE\s(.*)\s";
        string CookieDecoder = "\"id\";s:\\d+:\"(\\d+)\".*\"pw\";s:32:\"(\\w{32})\";}";
        public string Cookie = String.Empty;
        string URLDecode(string input)
        {
            input = input.Replace("%3A", ":");
            input = input.Replace("%7Bs", "{");
            input = input.Replace("%22", "\"");
            input = input.Replace("%3B", ";");
            input = input.Replace("%7D", "}");
            return input;
        }

        private void FormCookieSelect_Load(object sender, EventArgs e)
        {
            cookies.Items.Clear();
            StreamReader s = null;
            Match m;
            String content, cookie;

            DirectoryInfo iedir = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.Cookies));
            DirectoryInfo ffdir = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + Path.DirectorySeparatorChar + "Mozilla" + Path.DirectorySeparatorChar + "Firefox" + Path.DirectorySeparatorChar + "Profiles");
            StringCollection c = new StringCollection();
            if (iedir.Exists)
                foreach (FileInfo f in iedir.GetFiles("*.txt"))
                {
                    if (Regex.Match(f.Name, CookieFileRegex, RegexOptions.Singleline).Success)
                    //c.Add(f.FullName);
                    {
                        try
                        {
                            s = new StreamReader(f.FullName);
                            content = s.ReadToEnd();
                            s.Close();
                            if ((m = Regex.Match(content, CookieRegex, RegexOptions.Singleline)).Success)
                            {
                                UInt64 timeexp = Convert.ToUInt64(m.Groups[2].Value) + (Convert.ToUInt64(m.Groups[3].Value) << 32);
                                UInt64 timecreated = Convert.ToUInt64(m.Groups[4].Value) + (Convert.ToUInt64(m.Groups[5].Value) << 32);
                                DateTime dt = DateTime.FromFileTimeUtc((long)timeexp);
                                DateTime dtcreated = DateTime.FromFileTimeUtc((long)timecreated);
                                Match m2 = Regex.Match(URLDecode(m.Groups[1].Value),CookieDecoder);
                                ListViewItem i = new ListViewItem(m2.Groups[1].Value, 0, cookies.Groups[0]);
                                i.Tag = m.Groups[1].Value;
                                i.SubItems.Add(m2.Groups[2].Value.Substring(0, 6) + "...");
                                i.SubItems.Add(dtcreated.ToString());
                                i.SubItems.Add(dt.ToString());
                                cookies.Items.Add(i);
                            }
                        }
                        catch(Exception ex)
                        {
                            if (s != null)
                                s.Close();
                            MessageBox.Show(ex.Message);
                        }
                    }

                }
            if (ffdir.Exists)
                foreach (DirectoryInfo d in ffdir.GetDirectories())
                {
                    try
                    {
                        string value = string.Empty;
                        DateTime expiry = DateTime.MinValue;
                        if (File.Exists(Path.Combine(d.FullName, "cookies.sqlite")))
                        {
                            SQLiteConnection sql = new SQLiteConnection("Data Source=" + Path.Combine(d.FullName, "cookies.sqlite") + ";Version=3;");
                            sql.Open();
                            SQLiteCommand cmd = sql.CreateCommand();
                            //cmd.CommandText = "SELECT * FROM cookies";
                            cmd.CommandText = "select value,expiry from moz_cookies WHERE name='COOKIE' AND host='.esl.eu';";
                            //cmd.
                            SQLiteDataReader datareader = cmd.ExecuteReader();
                            if (datareader.Read())
                            {
                                value = datareader.GetString(0);
                                expiry = new DateTime(1970, 1, 1).AddSeconds(datareader.GetInt64(1));
                            }
                        }
                        else if (File.Exists(Path.Combine(d.FullName, "cookies.txt")))
                        {
                            using (s = new StreamReader(d.FullName + Path.DirectorySeparatorChar + "cookies.txt"))
                            {
                                string ffcookietxtcontent = s.ReadToEnd();
                                m = Regex.Match(ffcookietxtcontent, FFCookieRegex);
                                if (m.Success)
                                {
                                    expiry = new DateTime(1970, 1, 1).AddSeconds(Convert.ToUInt64(m.Groups[1].Value));
                                    value = m.Groups[2].Value;
                                }
                            }
                        }
                        Match m2 = Regex.Match(URLDecode(value), CookieDecoder);
                        if (m2.Success)
                        {
                            ListViewItem i = new ListViewItem(m2.Groups[1].Value, 1, cookies.Groups[1]);
                            i.Tag = value;
                            i.SubItems.Add(m2.Groups[2].Value.Substring(0, 6) + "...");
                            i.SubItems.Add("");
                            i.SubItems.Add(expiry.ToString());
                            cookies.Items.Add(i);
                        }
                    }
                    catch(Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
        }

        private void cookies_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cookies.SelectedItems.Count == 1)
            {
                bOK.Enabled = true;
                Cookie = (string)cookies.SelectedItems[0].Tag;
            }
            else
            {
                bOK.Enabled = false;
                Cookie = String.Empty;
            }
        }
    }
}